package com.cutefool.zero.code.admin.meta.model.context;

import com.cutefool.rds.template.RdsTemplate;
import com.cutefool.zero.code.admin.dbms.support.DbmsMetas;
import com.cutefool.zero.code.core.domain.Db;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class RdsTemplateContext {

    public Map<Long, RdsTemplate> context = new ConcurrentHashMap<>();

    public RdsTemplate get(Db db) {
        RdsTemplate rdsTemplate = context.get(db.getId());
        if (Objects.isNull(rdsTemplate)) {
            HikariDataSource hikariDataSource = DbmsMetas.dataSource(db);
            JdbcTemplate jdbcTemplate = new JdbcTemplate(hikariDataSource);
            rdsTemplate = new RdsTemplate(jdbcTemplate);
            context.put(db.getId(), rdsTemplate);
        }
        return rdsTemplate;
    }

}
